package org.yray.sip.factory;


import lombok.extern.slf4j.Slf4j;
import org.apache.tomcat.util.buf.HexUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.yray.sip.factory.impl.RtpReceiverA;
import org.yray.sip.factory.inet.IRtpFactory;
import org.yray.sip.rtp.sender.ISipSessionCache;
import org.yray.sip.server.SipServerContext;
import org.yray.sip.server.SipSession;
import org.yray.sip.utils.ByteUtils;
import org.yray.sip.utils.IcspBeanHolder;

import java.util.concurrent.atomic.AtomicLong;

@Component
@Slf4j
public class RtpFactory implements IRtpFactory {

    private static final AtomicLong cal=new AtomicLong(0);
    @Autowired
    private IdRuleComponent  idRuleComponent;

    @Autowired
    private RtpReceiverA rtpReceiverA;





    @Override
    public void formatRtp(byte[] bs, SipServerContext ssc, String senderIpPort) {
        log.debug("-------------------rtp---------------------");
        log.debug(HexUtils.toHexString(bs));
        //把对新端的RTP报文IP及端口号转换成callId存起来
        exchangeRtpIpPort(bs,senderIpPort);
        Long ssrc= ByteUtils.uBytes2IntSip(new byte[]{bs[8],bs[9],bs[10],bs[11]});
        String callId= IcspBeanHolder.getBean(ISipSessionCache.class).getCallIdBySsrc(ssrc);
        //这里是掉包了，也可能是挂了一端，另一端没挂
        if(callId==null)
        {
            if(cal.incrementAndGet()%500==0) {
                log.info("ssrc get callid is null,{}", ssrc);


            }
            return;
        }
        rtpReceiverA.formatRtp(bs,ssc,callId);

    }

    /***
     * 把对新端的RTP报文IP及端口号转换成callId存起来
     * @param bs
     * @param senderIpPort
     */
    private void exchangeRtpIpPort(byte[] bs,String senderIpPort)
    {
        String callId= IcspBeanHolder.getBean(ISipSessionCache.class).getAndRemoveRecvPort(senderIpPort);
        if(callId!=null)
        {
            long ssrc=ByteUtils.uBytes2Long(bs[8],bs[9],bs[10],bs[11]);
            log.info("exchangeRtpIpPort,{},ssrc={}",senderIpPort,ssrc);
            //String ssrc= HexUtils.toHexString(new byte[]{bs[8],bs[9],bs[10],bs[11]});

            SipSession session=IcspBeanHolder.getBean(ISipSessionCache.class).get(callId);
            session.setSideSsrc(ssrc);
            IcspBeanHolder.getBean(ISipSessionCache.class).putSsrc2CallId(ssrc,callId);
        }
    }
}
